# -*- coding: utf-8 -*-

###########################################################################
#
#   Copyright (c) 2020  Bresee, Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
###########################################################################

# oss operation func

# from typing_extensions import ParamSpecArgs
import oss2
import utils.config.websvrini as ini
import utils.common.initres as initres
import utils.common.func as func
import utils.common.log as log
from editapi.compose.oss_operation import Bucket
from tqdm import tqdm


class WebBucket:
    def __init__(self, access_key_id, access_key_secret, bucket_name):
        # auth = oss2.Auth('LTAI5tEp8oaTvbntixKcoqgc',
        #                  'WSZptFbM4JcyVftHm4OYtpx7i7ADtt')
        
        auth = oss2.Auth(access_key_id, access_key_secret)
        self.endpoint = "https://oss-cn-hangzhou-internal.aliyuncs.com"  
        self.bucket_name = bucket_name
        # self.__bucket = oss2.Bucket(
        #     auth, 'https://oss-cn-hangzhou.aliyuncs.com', 'cc-bucket-proivate')
        self.__bucket = oss2.Bucket(auth, self.endpoint, bucket_name)

    def upload_file(self, file_path, oss_obj_name) -> bool:
        """
        
        oss_obj_name: 
            'abc.mp4'
            'new_dir/def.jpg' new_dir

        return (bool, str), bool-false for fail, str stores the err-msg
        """
        # headers_ = {'x-oss-forbid-overwrite': 'true'}
        headers_ = {"x-oss-forbid-overwrite": "false"}
        oss_obj_full_name = oss_obj_name
        res = self.__bucket.put_object_from_file(oss_obj_full_name, file_path, headers_)

        url = f"https://{self.bucket_name}.oss-cn-hangzhou.aliyuncs.com/{oss_obj_name}"

        if res.status == 200:
            log.logging.info((oss_obj_full_name + " upload ok"))
            return True, url
        else:
            log.logging.error(("upload failed, res.status: " + res.status))
            return False, ""

    def remove_file(self, oss_obj_name) -> oss2.models.RequestResult:
        """
        not used func
        """
        res = self.__bucket.delete_object(oss_obj_name)

        return res

    def list_file(self, path: str) -> list:
        
        lst = []
        for obj in oss2.ObjectIterator(self.__bucket, prefix=f"{path}/", delimiter="/"):
          
            if obj.is_prefix(): 
                print("directory: " + obj.key)
                pass
            else:  
                lst.append(obj.key)
        return lst

    def list_file_type(self, path: str, type: str) -> list:
       
        type = "." + type
        lst = []
        for obj in oss2.ObjectIteratorV2(self.__bucket, prefix=f"{path}/"):
           
            if type in obj.key:
                lst.append(obj.key)
        return lst

    def download(self, file_path, download_path):
        object_stream = self.__bucket.get_object(file_path)
        total = int(object_stream.headers.get("content-length", 0))
        with open(download_path, "wb") as file, tqdm(
            desc=download_path,
            total=total,
            unit="iB",
            unit_scale=True,
            unit_divisor=1024,
        ) as bar:
            for data in object_stream:
                size = file.write(data)
                bar.update(size)


_templateOSS = None
_webOSS = None
if initres.YUN_WORKMODE:
    iniPath = ""
    iniPath = initres.iniPath()
    _templateDic = ini.get_oss(iniPath)
    _templateOSS = Bucket(
        _templateDic["access_key_id"],
        _templateDic["access_key_secret"],
        _templateDic["end_point"],
        _templateDic["template_bucket"],
        "",
    )

    _webOSS = WebBucket(
        _templateDic["access_key_id"],
        _templateDic["access_key_secret"],
        _templateDic["web_bucket"],
    )


def upload_template(filename):
    
    if _templateOSS is not None:
        ok, retname = _templateOSS.shadow_upload(filename)
    else:
        retname = initres.localUrl + filename.split("/")[-1]

    return retname


def upload_webRes(filename):
    
    if _webOSS is not None:
        if filename[0] == "/":
            ok, retname = _webOSS.upload_file(filename, filename[1:])
        else:
            ok, retname = _webOSS.upload_file(filename, filename)
    else:
        retname = initres.localUrl + filename.split("/")[-1]

    log.logging.info(retname)
    return retname


def delete_webRes(filename):
    
    if _webOSS is not None:
        print(filename)
        retname = _webOSS.remove_file(filename)
    return retname


def list_file(path):
    if _webOSS is not None:
        pass


if __name__ == "__main__":
    pass
    # go to cloud_edit.py to test
